import os.path
from config.configs import DATA_PATH, DESKTOP_PATH, TRADE_URL
import requests
from tools.funciton import read_xlsx_file, get_erp_token, read_json_file, write_json_file
from time import sleep
import pandas as pd
import pymongo

trade = pymongo.MongoClient(TRADE_URL).tradingMarketSneaker


def get_size_conversion():
    """获取kream尺码"""
    original_path = os.path.join(DESKTOP_PATH, '炮哥最新库存.csv')
    df = pd.read_csv(original_path)
    df.to_excel(os.path.join(DESKTOP_PATH, '炮哥最新库存.xlsx'), index=False)
    arts = [i.replace('瑕疵', '') for i in read_xlsx_file(os.path.join(DESKTOP_PATH, '炮哥最新库存.xlsx'), 3)]
    new_arts = list(set(arts))
    sizes = read_xlsx_file(os.path.join(DESKTOP_PATH, '炮哥最新库存.xlsx'), 4)
    li, items = [], []
    dic = read_json_file(os.path.join(DATA_PATH, 'kreamsizes.json'))
    headers = {
        'x-internal-access': "mI7lfclmb8tyCDhMgc1gTz6wZVKEQ82f",
    }
    for i in range(len(new_arts)):
        if new_arts[i] not in dic:
            url = f"https://base.dahood.tech/conversion/page?articleNumber={new_arts[i]}&entire=true"
            response = requests.request("GET", url, headers=headers).json()
            if 'data' not in response:
                print(f"{new_arts[i]}没有获取到口袋尺码信息")
            else:
                dic[response['data']['list'][0]['articleNumber']] = [{"dewu": i['measure'], 'platform': i['size']} for i
                                                                     in response['data']['list']]
            sleep(0.3)
    for i in range(len(sizes)):
        kream_item = dic[str(arts[i])]
        kream = [k['platform'] for k in kream_item if convert_size(k['dewu']) == convert_size(str(sizes[i]))]
        if len(kream) > 0:
            li.append(kream[0])
        else:
            li.append('')
    write_json_file(os.path.join(DATA_PATH, 'kreamsizes.json'), dic)
    df['Kream尺码'] = li
    df.to_excel(os.path.join(DESKTOP_PATH, '炮哥最新库存.xlsx'), index=False)


def convert_size(size):
    return size.replace('⅓', '').replace('⅔', '.5').replace('½', '.5')


def write_excel_pandas(data, columns='kream货号', file_name='kream货号.xlsx'):
    df = pd.DataFrame(data, columns=[columns])
    df.to_excel(file_name, index=False)


def get_kream_product(aim):
    """获取kream商品"""
    s, li, arts_len = 0, [], 0
    while arts_len < aim:
        if s == 0:
            url = f"https://api.kream.co.kr/api/h/tabs/ranking/?popular_filter=buy&category_filter=38&date_range_filter=weekly&&request_key=e327ca09-da93-4c97-b3be-07776ec9b02e"
        else:
            url = f"https://api.kream.co.kr/api/h/tabs/ranking/?popular_filter=buy&category_filter=38&date_range_filter=weekly&&request_key=e327ca09-da93-4c97-b3be-07776ec9b02e&cursor={s+1}"
        headers = {
            'accept': '*/*',
            'accept-language': 'zh-CN,zh;q=0.9',
            'origin': 'https://kream.co.kr',
            'priority': 'u=1, i',
            'referer': 'https://kream.co.kr/?tab=home_ranking_v2&popular_filter=buy',
            'sec-ch-ua': '"Google Chrome";v="135", "Not-A.Brand";v="8", "Chromium";v="135"',
            'sec-ch-ua-mobile': '?0',
            'sec-ch-ua-platform': '"macOS"',
            'sec-fetch-dest': 'empty',
            'sec-fetch-mode': 'cors',
            'sec-fetch-site': 'same-site',
            'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/135.0.0.0 Safari/537.36',
            'x-kream-api-version': '42',
            'x-kream-client-datetime': '20250417104410+0800',
            'x-kream-device-id': 'web;9b4a45ff-3c76-40bc-b154-f95afca6548d',
            'x-kream-web-build-version': '6.9.2',
            'x-kream-web-request-secret': 'kream-djscjsghdkd'
        }
        datas = requests.request("GET", url, headers=headers).json()['items']
        # print(f"第{s + 1}页数据获取成功", datas)
        origin_len = len(li)
        for i in range(len(datas)):
            # if datas[i]['display_type'] == 'product' and datas[i]['product']['release']['style_code'] not in li:
            #     li.append(str(datas[i]['product']['release']['style_code']))
            # else:
            print(datas[i])
            if 'product_item' in datas[i]:
                li.append(datas[i]['product_item']['name'])
        s += 1
        arts_len = len(li)
        if arts_len == origin_len:
            break
    write_excel_pandas(li)
    get_size_conversion()


def paoge_stock_export():
    pipeline = [
        {
            "$match": {
                "merchantCode": "486561",
                "warehouseCode": {"$regex": "Seoul"}
            }
        },
        {
            "$lookup": {
                "from": "spus",
                "localField": "spuId",
                "foreignField": "spuId",
                "as": "spu"
            }
        },
        {
            "$lookup": {
                "from": "skus",
                "localField": "skuId",
                "foreignField": "skuId",
                "as": "sku"
            }
        },
        {
            "$lookup": {
                "from": "appointments",
                "localField": "appointNo",
                "foreignField": "appointNo",
                "as": "app"
            }
        },
        {
            "$lookup": {
                "from": "merchants",
                "localField": "merchantCode",
                "foreignField": "code",
                "as": "mer"
            }
        },
        {
            "$addFields": {
                "createdAt": {
                    "$add": ["$createdAt", 8 * 60 * 60 * 1000]
                }
            }
        },
        {
            "$addFields": {
                "spu": {
                    "$arrayElemAt": ["$spu", 0]
                },
                "sku": {
                    "$arrayElemAt": ["$sku", 0]
                },
                "mer": {
                    "$arrayElemAt": ["$mer", 0]
                },
                "app": {
                    "$arrayElemAt": ["$app", 0]
                },
                "createdAt": {
                    "$toDate": "$createdAt"
                }
            }
        },
        {
            "$addFields": {
                "sku": {
                    "$switch": {
                        "branches": [
                            {
                                "case": {
                                    "$regexMatch": {
                                        "input": "$sku.properties",
                                        "regex": "尺码"
                                    }
                                },
                                "then": {
                                    "$split": [
                                        "$sku.properties",
                                        '尺码":"'
                                    ]
                                }
                            }
                        ],
                        "default": "$sku.properties"
                    }
                }
            }
        },
        {
            "$addFields": {
                "sku": {
                    "$arrayElemAt": ["$sku", 1]
                }
            }
        },
        {
            "$addFields": {
                "sku": {
                    "$split": ["$sku", '"}']
                },
                "createdAt": {
                    "$dateToString": {
                        "format": "%Y-%m-%d %H:%M:%S",
                        "date": {
                            "$toDate": "$createdAt"
                        }
                    }
                }
            }
        },
        {
            "$project": {
                "_id": 0,
                "预约单号": "$appointNo",
                "商家编号": "$merchantCode",
                "商家名称": "$mer.name",
                "货号": "$spu.articleNumber",
                "尺码": {
                    "$arrayElemAt": ["$sku", 0]
                },
                "唯一码": "$uniqueCode",
                "货架号": "$shelfCode",
                "入库数量": "$inStockQty",
                "在仓数量": "$qty",
                "物流单号": "$app.expressNo",
                "入库时间": "$createdAt",
                "uniqueCode": {
                    "$split": ["$uniqueCode", ":"]
                }
            }
        },
        {
            "$addFields": {
                "source": {
                    "$arrayElemAt": ["$uniqueCode", 1]
                }
            }
        },
        {
            "$lookup": {
                "from": "stockdeposits",
                "localField": "source",
                "foreignField": "uniqueCode",
                "as": "result"
            }
        },
        {
            "$unwind": {
                "path": "$result"
            }
        },
        {
            "$addFields": {
                "国内单号": "$result.expressNo",
                "成本价": "$result.costUnitPrice"
            }
        },
        {
            "$unset": "uniqueCode"
        },
        {
            "$unset": "source"
        },
        {
            "$unset": "result"
        }
    ]
    data = list(trade.stockdeposits.aggregate(pipeline))
    df = pd.DataFrame(data)
    df.to_csv(os.path.join(DESKTOP_PATH, '炮哥最新库存.csv'), index=False, encoding='utf-8-sig')
    original_path = os.path.join(DESKTOP_PATH, '炮哥最新库存.csv')
    df = pd.read_csv(original_path)
    df.to_excel(os.path.join(DESKTOP_PATH, '炮哥最新库存.xlsx'), index=False)
    arts = [i.replace('瑕疵', '') for i in read_xlsx_file(os.path.join(DESKTOP_PATH, '炮哥最新库存.xlsx'), 3)]
    new_arts = list(set(arts))
    sizes = read_xlsx_file(os.path.join(DESKTOP_PATH, '炮哥最新库存.xlsx'), 4)
    li, items = [], []
    dic = read_json_file(os.path.join(DATA_PATH, 'kreamsizes.json'))
    headers = {
        'x-internal-access': "mI7lfclmb8tyCDhMgc1gTz6wZVKEQ82f",
    }
    for i in range(len(new_arts)):
        if new_arts[i] not in dic:
            url = f"https://base.dahood.tech/conversion/page?articleNumber={new_arts[i]}&entire=true"
            response = requests.request("GET", url, headers=headers).json()
            if 'data' not in response:
                print(f"{new_arts[i]}没有获取到口袋尺码信息")
            else:
                dic[response['data']['list'][0]['articleNumber']] = [{"dewu": i['measure'], 'platform': i['size']} for i
                                                                     in response['data']['list']]
            sleep(0.3)
    for i in range(len(sizes)):
        kream_item = dic[str(arts[i])]
        kream = [k['platform'] for k in kream_item if convert_size(k['dewu']) == convert_size(str(sizes[i]))]
        if len(kream) > 0:
            li.append(kream[0])
        else:
            li.append('')
    write_json_file(os.path.join(DATA_PATH, 'kreamsizes.json'), dic)
    df['Kream尺码'] = li
    df.to_excel(os.path.join(DESKTOP_PATH, '炮哥最新库存.xlsx'), index=False)


def paoge_stock_out_export():
    """获取kream尺码"""
    pipeline = [
        {
            "$match": {
                "merchantCode": "486561"
            }
        },
        {
            "$unwind": {
                "path": "$skuList"
            }
        },
        {
            "$lookup": {
                "from": "skus",
                "localField": "skuList.skuId",
                "foreignField": "skuId",
                "as": "sku"
            }
        },
        {
            "$lookup": {
                "from": "spus",
                "localField": "skuList.spuId",
                "foreignField": "spuId",
                "as": "spu"
            }
        },
        {
            "$addFields": {
                "createdAt": {
                    "$add": ["$createdAt", 8 * 60 * 60 * 1000]
                },
                "pickedTime": {
                    "$add": ["$pickedTime", 8 * 60 * 60 * 1000]
                },
                "deliverTime": {
                    "$add": ["$deliverTime", 8 * 60 * 60 * 1000]
                }
            }
        },
        {
            "$addFields": {
                "spu": {
                    "$arrayElemAt": ["$spu", 0]
                },
                "sku": {
                    "$arrayElemAt": ["$sku", 0]
                },
                "createdAt": {
                    "$toDate": "$createdAt"
                },
                "pickedTime": {
                    "$toDate": "$pickedTime"
                },
                "deliverTime": {
                    "$toDate": "$deliverTime"
                }
            }
        },
        {
            "$addFields": {
                "sku": {
                    "$switch": {
                        "branches": [
                            {
                                "case": {
                                    "$regexMatch": {
                                        "input": "$sku.properties",
                                        "regex": "尺码"
                                    }
                                },
                                "then": {
                                    "$split": [
                                        "$sku.properties",
                                        '尺码":"'
                                    ]
                                }
                            }
                        ],
                        "default": "$sku.properties"
                    }
                }
            }
        },
        {
            "$addFields": {
                "sku": {
                    "$arrayElemAt": ["$sku", 1]
                }
            }
        },
        {
            "$addFields": {
                "sku": {
                    "$split": ["$sku", '"}']
                },
                "createdAt": {
                    "$dateToString": {
                        "format": "%Y-%m-%d %H:%M:%S",
                        "date": {
                            "$toDate": "$createdAt"
                        }
                    }
                },
                "pickedTime": {
                    "$dateToString": {
                        "format": "%Y-%m-%d %H:%M:%S",
                        "date": {
                            "$toDate": "$pickedTime"
                        }
                    }
                },
                "deliverTime": {
                    "$dateToString": {
                        "format": "%Y-%m-%d %H:%M:%S",
                        "date": {
                            "$toDate": "$deliverTime"
                        }
                    }
                }
            }
        },
        {
            "$project": {
                "_id": 0,
                "出库单号": "$outStockNo",
                "类型": "$type",
                "商品名称": "$spu.title",
                "商品货号": "$spu.articleNumber",
                "商品尺码": {
                    "$arrayElemAt": ["$sku", 0]
                },
                "出库数量": "$skuList.outQty",
                "唯一码": "$skuList.uniqueCode",
                "仓库": "$warehouseCode",
                "创建时间": "$createdAt",
                "拣货时间": "$pickedTime",
                "发货时间": "$deliverTime"
            }
        }
    ]
    data = list(trade.stockoutorders.aggregate(pipeline))
    df = pd.DataFrame(data)
    df.to_csv(os.path.join(DESKTOP_PATH, '炮哥出库单导出.csv'), index=False, encoding='utf-8-sig')
    original_path = os.path.join(DESKTOP_PATH, '炮哥出库单导出.csv')
    df = pd.read_csv(original_path)
    df.to_excel(os.path.join(DESKTOP_PATH, '炮哥出库单导出.xlsx'), index=False)
    arts = [i.replace('瑕疵', '') for i in read_xlsx_file(os.path.join(DESKTOP_PATH, '炮哥出库单导出.xlsx'), 3)]
    new_arts = list(set(arts))
    sizes = read_xlsx_file(os.path.join(DESKTOP_PATH, '炮哥出库单导出.xlsx'), 4)
    li, items = [], []
    dic = read_json_file(os.path.join(DATA_PATH, 'kreamsizes.json'))
    headers = {
        'User-Agent': 'Apifox/1.0.0 (https://apifox.com)',
        'x-internal-access': "mI7lfclmb8tyCDhMgc1gTz6wZVKEQ82f",
        'Accept': '*/*',
        'Host': 'apiv2.dingstock.net',
        'Connection': 'keep-alive'
    }
    for i in range(len(new_arts)):
        if new_arts[i] not in dic:
            url = f"https://base.dahood.tech/conversion/page?articleNumber={new_arts[i]}&entire=true"
            response = requests.request("GET", url, headers=headers).json()
            if response['data']['list'] == []:
                print(f"{new_arts[i]}没有获取到口袋尺码信息")
                dic[new_arts[i]] = [{"dewu": "", 'platform': ""}]
            else:
                dic[response['data']['list'][0]['articleNumber']] = [{"dewu": i['measure'], 'platform': i['size']} for i
                                                                     in response['data']['list']]
            sleep(0.3)
    for i in range(len(sizes)):
        kream_item = dic[str(arts[i])]
        kream = [k['platform'] for k in kream_item if convert_size(k['dewu']) == convert_size(str(sizes[i]))]
        if len(kream) > 0:
            li.append(kream[0])
        else:
            li.append('')
    write_json_file(os.path.join(DATA_PATH, 'kreamsizes.json'), dic)
    df['Kream尺码'] = li
    df.to_excel(os.path.join(DESKTOP_PATH, '炮哥出库单导出.xlsx'), index=False)


# paoge_stock_export()
get_kream_product(1000)